package com.example.mahao_final.UI

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.RatingBar
import android.widget.Toast
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.lifecycleScope
import com.example.mahao_final.R
import com.example.mahao_final.database.BlogDatabase
import com.example.mahao_final.entity.Blog
import com.google.android.flexbox.FlexboxLayout
import kotlinx.coroutines.launch
import android.content.Context

class AddBlogFragment : DialogFragment(R.layout.fragment_add_blog) {

    private lateinit var etBlogTitle: EditText
    private lateinit var etBlogDescription: EditText
    private lateinit var etBlogContent: EditText
    private lateinit var btnAddBlog: Button
    private lateinit var btnDelete: Button
    private lateinit var btnAddTag: Button
    private lateinit var ratingBar: RatingBar
    private lateinit var llTags: FlexboxLayout

    private val tagList = mutableListOf<String>()
    private val blogDao by lazy { BlogDatabase.getDatabase(requireContext()).blogDao() }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // 初始化视图
        etBlogTitle = view.findViewById(R.id.et_blog_title)
        etBlogDescription = view.findViewById(R.id.et_blog_description)
        etBlogContent = view.findViewById(R.id.et_blog_content)
        btnAddBlog = view.findViewById(R.id.btn_add)
        btnDelete = view.findViewById(R.id.btn_delete)
        btnAddTag = view.findViewById(R.id.btn_add_tag)
        ratingBar = view.findViewById(R.id.rating_bar)
        llTags = view.findViewById(R.id.ll_tags)

        // 设置对话框宽度
        dialog?.window?.setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)

        // 获取当前用户的昵称
        val currentUserNickname = getCurrentUserNickname()

        // 点击 "添加标签" 按钮
        btnAddTag.setOnClickListener {
            if (tagList.size < 4) {
                showTagInputDialog()
            } else {
                Toast.makeText(requireContext(), "最多可以添加四个标签!", Toast.LENGTH_SHORT).show()
            }
        }

        // 点击 "添加博客" 按钮
        btnAddBlog.setOnClickListener {
            addBlog(currentUserNickname)
        }

        // 点击 "删除" 按钮
        btnDelete.setOnClickListener {
            dismiss()
        }
    }

    private fun addBlog(author: String) {
        val title = etBlogTitle.text.toString().trim()
        val description = etBlogDescription.text.toString().trim()
        val content = etBlogContent.text.toString().trim()
        val difficulty = ratingBar.rating

        if (title.isEmpty() || description.isEmpty() || content.isEmpty() || tagList.isEmpty()) {
            Toast.makeText(requireContext(), "所有字段必须填写！", Toast.LENGTH_SHORT).show();
        } else {
            // 创建 Blog 对象，作者使用当前用户的昵称
            val blog = Blog(
                title = title,
                description = description,
                content = content,
                author = author,  // 使用默认的当前用户昵称
                difficulty = difficulty,
                tags = tagList
            )

            // 使用协程将博客插入数据库
            lifecycleScope.launch {
                blogDao.insert(blog)
                Toast.makeText(requireContext(), "博客添加成功!", Toast.LENGTH_SHORT).show();
                dismiss()
            }
        }
    }

    // 获取当前用户的昵称
    private fun getCurrentUserNickname(): String {
        val sharedPreferences = requireContext().getSharedPreferences("UserPrefs", Context.MODE_PRIVATE)
        return sharedPreferences.getString("nickname", "Unknown") ?: "Unknown"  // 获取当前用户的昵称
    }

    // 显示标签输入对话框
    private fun showTagInputDialog() {
        val tagDialogView = LayoutInflater.from(requireContext()).inflate(R.layout.dialog_tag_input, null)
        val tagInputField: EditText = tagDialogView.findViewById(R.id.et_tag)
        val btnAddTagToList: Button = tagDialogView.findViewById(R.id.btn_add_tag_to_list)

        val tagDialog = android.app.AlertDialog.Builder(requireContext())
            .setView(tagDialogView)
            .create()

        // 添加标签到列表
        btnAddTagToList.setOnClickListener {
            val tag = tagInputField.text.toString().trim()
            if (tag.isNotEmpty() && !tagList.contains(tag)) {
                tagList.add(tag)

                // 创建标签按钮
                val tagView = LayoutInflater.from(requireContext()).inflate(R.layout.tag_button, null) as LinearLayout
                val tagButton: Button = tagView.findViewById(R.id.btn_tag)
                tagButton.text = tag

                // 点击标签删除
                tagButton.setOnClickListener {
                    tagList.remove(tag)
                    llTags.removeView(tagView)
                }

                // 添加标签到 FlexboxLayout
                llTags.addView(tagView)

                tagDialog.dismiss()
            } else {
                Toast.makeText(requireContext(), "请输入有效的标签", Toast.LENGTH_SHORT).show();
            }
        }

        tagDialog.show()
    }
}
